# -*- Mode: perl; indent-tabs-mode: nil -*-
#
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is the PreferredEmail Bugzilla Extension.
#
# The Initial Developer of the Original Code is IBM LTC
# Portions created by the Initial Developer are Copyright (C) 2010 the
# Initial Developer. All Rights Reserved.
#
# Contributor(s):
#   Tiago Rodrigues de Mello <timello@linux.vnet.ibm.com>

package Bugzilla::Extension::PreferredEmail::Util;
use strict;
use base qw(Exporter);

use Bugzilla::Error;
use Bugzilla::Extension::PreferredEmail::Constants;

our @EXPORT = qw(
    get_preferred_email
    validate_preferred_email
);

sub get_preferred_email {
    my ($login_name) = @_;
    my $preferred_email = Bugzilla->dbh->selectrow_array(
      'SELECT extern_id FROM profiles WHERE login_name = ?', undef, $login_name);
    return $preferred_email || '';
}

sub validate_preferred_email {
    my ($preferred_email) = @_;

    if ($preferred_email !~ m/${\EMAIL_REG_EXP}/) {
        ThrowUserError('not_valid_pref_email', { email => $preferred_email });
    }

    my $preferred_email_exists = Bugzilla->dbh->selectrow_array(
        'SELECT login_name FROM profiles
         WHERE extern_id = ? AND login_name <> ?', undef,
        ($preferred_email, Bugzilla->user->login));

    if ($preferred_email_exists) {
        ThrowUserError('email_already_in_use',
                       { email => $preferred_email,
                         user  => $preferred_email_exists });
    }
}

1;
